<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;


use Illuminate\Support\Facades\Validator;     // 后台表单验证
use Illuminate\Support\Facades\Hash;           // 哈希加密
use Illuminate\Support\Facades\Crypt;
use Mockery\Exception;           // crypt加密

class UserController extends Controller
{

    /* 1.查看用户信息, post  */
    public function about(Request $request) {
        //  php不允许请求头上的字段带有下划线的数据_,因为它会默认转换为-
        //  php不允许请求头上的字段带有驼峰习惯的数据,因为它会默认转换为小写
        $res = $request->header();
        $accesstoken = str_replace("bearer-","",$res['access-token'][0]);

        // 解析出用户信息， 再删除当前保存的token
        // 1.解析用户信息
        $userinfo = $this->verifyToken($accesstoken,'decrypt');

        return $this->responseTool(null,$userinfo, 200);
    }

    /* 2.更新用户信息，post  */
    public function update(Request $request) {
        //  php不允许请求头上的字段带有下划线的数据_,因为它会默认转换为-
        //  php不允许请求头上的字段带有驼峰习惯的数据,因为它会默认转换为小写
        //  当前会返回新的token;
        $res = $request->header();
        $accesstoken = str_replace("bearer-","",$res['access-token'][0]);

        // 解析出用户信息， 再删除当前保存的token
        // 1.解析用户信息
        $userinfo = $this->verifyToken($accesstoken,'decrypt');


        // 2、接收表单提交的数据
        $input = $request->all() ;
        // 或者  $input = request(['username', 'password']);
        //相当于python的POST.dict()

        //3．进行表单验证
        $rule = [
            'username'=>'required|between:2,18',
            'password'=>'required|between:6,18|alpha_dash',
            'sex'=>'required',
            'address'=>'required',
        ];
        $msg = [
            'username.required'=>'用户名不能为空',
            'username.between'=>'用户名长度必须在2-18位之间',
            'password.required'=>'密码不能为空',
            'password.between'=>'密码长度必须在6-18位之间',
            'password.alpha_dash'=>'密码必须是数组字母下滑线',
            'sex.required'=>'性别不能为空',
            'address.required'=>'地址不能为空',
        ];
        $validator = Validator::make($input,$rule,$msg) ;   // 表单数据, 验证规则, 错误信息
        if ($validator->fails()) {
            return  $this->responseTool($validator,null,403);
        }

        // 4.加密用户密码与新增数据
        $input['password'] = $this->verifyPwd($input['password']);
        $input["updateTime"] =  date('Y-m-d h:i:s', time());
        $input["isDelete"] =  '0';


        // 5.检查是否有同名的用户（禁止）
//        echo $userinfo['username'];
        $user = User::where(["username"=> $userinfo['username']]);
        if(!$user->first()){
            return $this->responseTool('修改失败！该用户名已经被注册',null,403 );
        }else{
            // 6. 生成新的token
            $token = $this->verifyToken(null,'encrypt',$userinfo['id']);

            // 7. 修改用户信息
            $input['token']=$token;
            $res = $user->update($input);

            return $this->responseTool('修改成功！',null,200, $token);
        }
    }

    /*刷新token, 暂不开启*/
    public function refresh() {
        return $this->respondWithToken(auth('api')->refresh());
    }



    /* 1.查询用户 get */
    public function search(Request $request)  {

        $username = $request->input('username','');
        $new_username  = str_replace(' ','',$username);
        // 1.检验空值
        if(strlen($new_username) == 0){
            return response()->json(['msg' => '查询的用户名不能为空！', 'code' => 403]);
        }

        // 2.清空当前用户的token
        $user = User::where(["username"=> $new_username]);
        if($user->first()){
            return $this->responseTool('查询成功！',$user->first(), 200);
        }
        return $this->responseTool('没有查询到相关用户！',null, 402);

    }

    /* 2.查询所有用户 post */
    public function searchAll(Request $request)  {
        $userArr = User::get();
        return $this->responseTool('获取数据成功',$userArr,200);
    }

    /* 3.查询所有注销的用户 post */
    public function searchDelAll(Request $request)  {
        $userArr = User::query()-> where('isDelete','1')->get();
//        $userArr = User::where(['isDelete'=>'1'])->get();
        return $this->responseTool('获取已注销成员列表',$userArr,200);
    }

    /* 4.查询所有非注销的用户 post */
    public function searchUseAll(Request $request)  {
        $userArr = User::query()->get();;
        // $userArr = User::where(['isDelete'=>'1'])->get();

        // 清除已经注销的用户
        $new_userArr = [];
        foreach($userArr as $key => $value){
            if($value['isDelete'] != '1'){
            // $new_userArr[$key] = $value;
               array_push($new_userArr,$value);
            }
        }
        return $this->responseTool('获取正常用户列表',$new_userArr,200);
    }




    //    工具类
    /* 返回token相关的数据*/
    protected function responseToken($token){
        return response()->json([
            'msg'=>'登录成功！',
            'access-token' => $token,
            'token-type' => 'bearer',
            'expires-in' => auth('api')->factory()->getTTL() / (60 * 24 ) . '天',
            'code'=>'200'
        ]);
    }

    /* 响应的工具方法 */
    //  return {msg:$msg, data:$data,code:$code};
    //  php没有对象与字典，但它的字符串索引数组就是类似结构
    public function responseTool($msg,  $data, $code, $token=null){
        if($token){
            return array('msg'=>$msg,'data'=>$data,'code'=>$code,'token'=>$token);
        }else{
            return array('msg'=>$msg,'data'=>$data,'code'=>$code);
        }
    }

    /* 密码Crypt加密算法 */
    public function verifyPwd($str, $mode="encrypt",$val=null){
        if ($mode == 'encrypt') {
            return Crypt::encrypt($str);   // 加密
        } else {
            if ($val == Crypt::decrypt($str)) {  // 解密
                return true;
            } else {
                return false;
            }
        }
    }


    /* token加密算法 */
    public function verifyToken($str, $mode="encrypt", $tokenid=null){
        if ($mode == 'encrypt') {
            // 传递从数据库返回的信息
            $user = $str;
            if($tokenid){
                return auth('api')->tokenById($tokenid);
            }else{
                return auth('api')->login($user);
            }
        } else {
            // 传递需要解析的token
            $accesstoken = $str;
            auth('api')->setToken($accesstoken);
            return auth('api')->user();
        }
    }
}
